# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
from functools import wraps
from cStringIO import StringIO

from google.appengine.api import users
from google.appengine.api import memcache

from django.http import HttpResponse, HttpResponseRedirect, urljoin
from django.shortcuts import render_to_response as django_render_to_response
from django.utils.html import escape, strip_tags
from django.template import loader
from django.utils import simplejson

from settings import Site_Settings
from apis import people_api, gear_api, outusers
from language import get_current_lang, save_current_lang, _, _m
from units import *

def get_units_settings(current_unit):
    return {
        "unit": current_unit,
        "units": UNITS_DISTANCE,
        "km_mile": KM_Mile[current_unit],
        "m_feet": M_Feet[current_unit],
        }

def my_render_to_response(*args, **kwargs):
    """
    Returns a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
    return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)

def render_to_response(templatefile, context):
    current_units = get_current_units()
    current_lang = get_current_lang()
    user = people_api.get_current_user()
    if user:
        if user.language != current_lang:
            save_current_lang(user.language)
            current_lang = user.language
        if user.units != current_units:
            save_current_units(user.units)
            current_units = user.units

    context["user"] = user
    context["isadmin"] = users.is_current_user_admin()
    context["outsiteuser"] = outusers.get_outsite_user()
    context["unit"] = get_units_settings(current_units)
    context["lang"] = current_lang
    context["site_settings"] = Site_Settings
    return my_render_to_response(templatefile, context)


def render_to_javasript(templatefile, context={}):
    current_units = get_current_units()
    current_lang = get_current_lang()
    user = people_api.get_current_user()
    if user:
        if user.language != current_lang:
            save_current_lang(user.language)
            current_lang = user.language
        if user.units != current_units:
            save_current_units(user.units)
            current_units = user.units

    #context["user"] = user
    #context["isadmin"] = users.is_current_user_admin()
    #context["outsiteuser"] = outusers.get_outsite_user()
    context["unit"] = get_units_settings(current_units)
    context["lang"] = current_lang
    context["site_settings"] = Site_Settings


    cache_key = "javascript_%s_%s_%s"%(templatefile,
                                          current_units, current_lang)
    cached_script = memcache.get(cache_key)
    if cached_script is None:
        cached_script = loader.render_to_string(templatefile, context)
        try:
            memcache.set(cache_key, cached_script)
        except Exception:
            logging.exception("memcache set error in render_to_javasript")

    resp = HttpResponse()
    resp['Content-Type'] = "text/javascript"
    resp.write(cached_script)
    return resp


def requires_site_admin(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if users.is_current_user_admin():
            return method(self, *args, **kwargs)
        return HttpResponseRedirect("/login/")

    return wrapper


def requires_site_user(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if people_api.get_current_user():
            return method(self, *args, **kwargs)
        return HttpResponseRedirect("/login/")

    return wrapper


def requires_outsite_user(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if outusers.get_outsite_user():
            return method(self, *args, **kwargs)
        return HttpResponseRedirect("/login/")

    return wrapper


def escape_and_strip(str):
    escaped = escape(strip_tags(str))
    if not isinstance(escaped, unicode):
        return unicode(escaped, 'utf-8').strip()
    else:
        return escaped.strip()


def unescape(string):
    return string and string.replace('&amp;', '&').replace('&lt;', '<').replace('&gt;', '>').replace('&quot;',
        '"').replace("&#39;", "")


def escape_parameters(dit):
    for key in dit:
        val = dit[key]
        if isinstance(val, str) or isinstance(val, unicode):
            dit[key] = escape_and_strip(val)
    return dit


def errorpage(msg):
    content = {"error_msg": msg}
    return render_to_response("error.html", content)


def post_activity_to_outsite(uid, activity_id):
    outsite_user = people_api.get_outuser_by_uid(uid)
    if not outsite_user:
        logging.warn("post_activity_to_outsite: no outsite user")
        return

    activity = people_api.get_activity_by_id(activity_id)
    if not activity:
        logging.warn("post_activity_to_outsite: no activity")
        return

    lang = activity.Rider.language
    msg = StringIO()
    s = _m("%0 [%1] on @MagiCycles迈记网 .", lang, _(activity.Action, lang), activity.Target.name)
    msg.write(s.encode("utf-8"))

    photourl = ""
    url = None
    lat = ""
    long = ""
    host = Site_Settings.get("host_site", "http://www.magicycles.com")
    if activity.Action == "Add a Bike":
        url = urljoin(host, "/gears/bike/%s" % activity.Target.id)
        photourl = activity.Target.photourl
    elif activity.Action == "Create a Route":
        url = urljoin(host, "/routes/%s" % activity.Target.id)
        photourl = activity.Target.preview_url
        lat = activity.Target.start_location.lat
        long = activity.Target.start_location.lon
    elif activity.Action == "Add a Ride":
        url = urljoin(host, "/rides/%s" % activity.Target.id)
        photourl = activity.Target.route.preview_url
        lat = activity.Target.route.start_location.lat
        long = activity.Target.route.start_location.lon
    elif activity.Action == "Join Team":
        url = urljoin(host, "/teams/%s" % activity.Target.id)
        photourl = activity.Target.photourl
        lat = activity.Target.location.lat
        long = activity.Target.location.lon
    elif activity.Action == "Add a Comment":
        url = urljoin(host, "/routes/%s" % activity.Target.route.id)
        photourl = activity.Target.photourl
        lat = activity.Target.location.lat
        long = activity.Target.location.lon
    elif activity.Action == "Add Favorite":
        url = urljoin(host, "/routes/%s" % activity.Target.id)
        photourl = activity.Target.preview_url
    elif activity.Action == "Remove Favorite":
        url = urljoin(host, "/routes/%s" % activity.Target.id)
        photourl = activity.Target.preview_url
    elif activity.Action == "Add a Friend":
        url = urljoin(host, "/riders/%s" % activity.Target.uid)
        photourl = activity.Target.photourl

    if photourl:
        photourl = unescape(photourl)
    else:
        photourl = ""
    if photourl and photourl.startswith("/"):
        photourl = urljoin(host, photourl)
    if url:
        msg.write(_("More...", lang).encode("utf-8"))
        msg.write(url.encode("utf-8"))
    msg = msg.getvalue()

    annotations = {"MagiCycles": {
        "site": host,
        "activity": activity.Action,
        "user": activity.Rider.uid,
    }}
    annotations = simplejson.dumps(annotations)

    outusers.post_activity(outsite_user, msg, photourl, annotations, lat, long)


def main():
    pass

if __name__ == '__main__':
    main()

